<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <style>
    .contaienr{
        
        width: 400px;
        margin:100px auto;
        text-align: center;
    }
    .wrapper{
        margin-top:20px;
    }
    .wrapper .box{
        display: inline-block;
        width: 100px;
        height: 100px;
        background-color: rgb(194, 142, 142);
    }
    .active{
        background-color: rgb(179, 185, 235) !important;
    }
    </style>
    
</head>
<body>
    <div class="contaienr">
        <button id="btn">变色</button>
        <div class="wrapper">
            <div class="box"></div>
            <div class="box"></div>
            <div class="box"></div>
        </div>
    </div>
    <script>
        var btn = document.getElementById('btn');
        var boxes = document.querySelectorAll('.box')
        //nodeList 可以用forEach
        boxes.forEach(function(el){
            console.log(el)
        })
        var boxes1 = document.getElementsByClassName('box')
        //HTMLCollection 不能用forEach
        // boxes1.forEach(function(el){
        //     console.log(el)
        // })
        //把HTMLCollection转换成数组的方式
        //var boxes1Arr = Array.from(boxes1)
        //var boxes2Arr = [...boxes1]
        //不推荐直接更改style而是通过修改class的方式改变元素的样式
        // btn.onclick = function(){
        //     boxes.forEach(function(el){
        //         if(!el.style.backgroundColor){
        //             el.style.backgroundColor = "green"
        //         }else{
        //             el.style.backgroundColor = ""
        //         }       
        //     })
        // }
        btn.onclick = function(){
            boxes.forEach(function(el){
                if(el.classList.contains('active')){
                    el.classList.remove('active')
                }else{
                    el.classList.add('active')
                }
            })
        }

       for(var i=0; i<boxes1.length; i++){
           boxes1[i].addEventListener('click',function(){
               console.log(i)
           })
       }

    </script>
</body>
</html>